package com.ljfresh.customer.interceptor;

import com.alibaba.fastjson.JSON;
import com.ljfresh.customer.common.CommonAttribute;
import com.ljfresh.customer.pojo.User;
import com.ljfresh.customer.utils.RedisUtils;
import org.apache.ibatis.plugin.Intercepts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;


/**
 * @author: Lucifer
 * @time: 2020/4/11-9:12
 */
public class ApiAuthInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    public ApiAuthInterceptor() {
        super();
    }

    private Set<Pattern> freeset = new HashSet<>();
    {
        freeset.add(Pattern.compile("/user/login"));
        freeset.add(Pattern.compile("/store/findStore"));
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        for (Pattern pattern : freeset) {
            if (pattern.matcher(uri).find()) {
                return true;
            }
        }
        String sessionId = request.getHeader("sessionId");
        if (StringUtils.isEmpty(sessionId)) {
            sessionId = request.getParameter("sessionId");
        }
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-type", "text/json;charset=UTF-8");
        PrintWriter writer;
        User user = null;
        try {
            Object obj = redisUtils.get(sessionId);
            user = JSON.parseObject(JSON.toJSONString(obj), User.class);
        } catch (Exception e) {
            e.printStackTrace();
            writer = response.getWriter();
            writer.write("{\"code\":105006,\"message\":\"用户未登录\"}");
            return false;
        }
        if (user != null) {
            //添加formid列表给用户
            request.setAttribute(CommonAttribute.CURRENT_USER, user);
            return true;
        } else {
            try {
                writer = response.getWriter();
                writer.write("{\"code\":105006,\"message\":\"用户未登录\"}");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }



}
